package com.chd.driversystem.util.network;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

import com.chd.driversystem.domain.Evaluation;
import com.chd.driversystem.domain.User;
import com.chd.driversystem.util.network.bean.DayData;
import com.chd.driversystem.util.network.bean.MonthData;
import com.chd.driversystem.util.network.bean.ResultMsg;
import com.chd.driversystem.util.network.bean.TokenManager;
import com.chd.driversystem.util.test.GetTestData;
import com.chd.driversystem.util.tools.MyApplication;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by shawnfly on 17-5-2.
 */

public class HttpManager {

    private static final String TAG = "HttpManager";
    //结果参数定义   暂时定义
    public static final int OP_SUCCESS = 0;
    public static final int OP_SERVER_DENY_ERR = -1;
    public static final int OP_CLIENT_ERR = -2;

    private static HttpAccess httpAccess = HttpAccess.getmInstance();

    public static HttpRetrofitAccess retrofitAccess = httpAccess.getRetrofitAccess();

    private static int errorCode = OP_SUCCESS;

    private static String errorMsg = "操作成功";

    private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");


    public static int getErrorCode() {
        return errorCode;
    }

    public static String getErrorMsg() {
        return errorMsg;
    }

    /**
     * 登录操作
     *
     * @param loginname 登录名
     * @param password  密码
     * @param isManager
     * @return
     */
    public static User userLogin(String loginname, String password, boolean isManager) {
        /***********测试，待实现*****************/
//        Integer isMg = isManager ? 0 : 1;
//        Call<Map<String, Object>> tokenCall = retrofitAccess.getToken(loginname, password, isMg);
//        Response<Map<String, Object>> response = null;
        User user = null;
//        try {
//            response = tokenCall.execute();
//            if (response.isSuccessful()) {
//                Map<String, Object> resultMap = response.body();
//                if (resultMap.get("msg") instanceof Double) {
//                    TokenManager.setToken((String) resultMap.get("ticket"));
//                    SharedPreferences pf = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
//                    SharedPreferences.Editor editor = pf.edit();
//                    editor.putString("ticket", (String) resultMap.get("ticket"));
//                    editor.apply();
                    user = GetTestData.getOneUser(loginname, password, isManager);
//                    errorMsg = "操作成功";
//                    Log.d(TAG, "userLogin: resultMap:" + resultMap);
//                } else {
//                    errorMsg = (String) resultMap.get("msg");
//                }
//            } else {
//                errorMsg = "网络错误";
//            }
//            errorCode = response.code();
//        } catch (IOException e) {
//            e.printStackTrace();
//            errorCode = OP_CLIENT_ERR;
//            errorMsg = "客户端错误"+e.toString();
//        }
        /**************************************/
        Log.d(TAG, "userLogin: errCode:" + errorCode + "; errMsg:" + errorMsg);
        return user;
    }

    public static User userSignUp(String loginname, String password, Integer job) {
        /***********测试，待实现*****************/

        Call<ResultMsg<Map<String, String>>> tokenCall = retrofitAccess.signUpUser(loginname, password, job);
        Response<ResultMsg<Map<String, String>>> response = null;
        User user = null;
        try {
            response = tokenCall.execute();
            if (response.isSuccessful()) {
                ResultMsg<Map<String, String>> resultMap = response.body();
                if (resultMap.getCode() == 1) {
                    TokenManager.setToken((String) resultMap.getData().get("ticket"));
                    SharedPreferences pf = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
                    SharedPreferences.Editor editor = pf.edit();
                    editor.putString("ticket", TokenManager.getToken());
                    editor.apply();

                    user = GetTestData.getOneUser(loginname, password, job == 0);
                    errorMsg = "操作成功";
                    Log.d(TAG, "userLogin: resultMap:" + resultMap);
                } else {
                    errorMsg = resultMap.getMsg();
                }
                errorCode=OP_SUCCESS;
            } else {
                errorMsg = "网络错误";
                errorCode=response.code();
            }
        } catch (IOException e) {
            e.printStackTrace();
            errorCode = OP_CLIENT_ERR;
            errorMsg = "客户端错误";
        }
        /**************************************/
        Log.d(TAG, "userSignUp: Code:" + errorCode + "; Msg:" + errorMsg);
        return user;
    }


    /**
     * 获取评价信息
     *
     * @return
     */
    public static List<Evaluation> getEvaluations(Long userId, Integer type) {
        List<Evaluation> evaluations = GetTestData.getEvaluations(userId, type);
        return evaluations;
    }


    public static List<User> getUserList(Long managerId) throws IOException {
        List<User> users = null;
        Call<ResultMsg<Map<String, List<String>>>> msgCall = retrofitAccess.getUserList(TokenManager.getToken());
        Response<ResultMsg<Map<String, List<String>>>> msgResponse = msgCall.execute();
        if (msgResponse.isSuccessful()) {
            ResultMsg<Map<String, List<String>>> resultMsg = msgResponse.body();
            if (resultMsg.getCode() == 1) {
                users = new ArrayList<>();
                GetTestData.getUserListByManagerId(managerId, users, resultMsg.getData().get("司机列表"));
                errorMsg = resultMsg.getMsg();
                errorCode = OP_SUCCESS;
            } else {
                errorMsg = resultMsg.getMsg();
                errorCode = OP_SERVER_DENY_ERR;
            }
        } else {
            errorCode = msgResponse.code();
            errorMsg = msgResponse.message();
        }
        return users;
    }

    public static List<Evaluation> getEvaluationsByUserList(List<User> users, Integer type) {
        List<Evaluation> evaluations = GetTestData.getEvaluationsByUserList(users, type);
        return evaluations;
    }

    public static DayData getDriverDataByDateRange(String driverId, Date startDate, Date endDate) throws IOException {
        DayData resultsMap = null;

        Call<ResultMsg<DayData>> msgCall =
                retrofitAccess.getDriverDataByDateRange(TokenManager.getToken(),
                        driverId,
                        dateFormat.format(startDate),
                        dateFormat.format(endDate));
        Response<ResultMsg<DayData>> msgResponse = msgCall.execute();
        Log.d(TAG, "getDriverDataByDateRange: msgUrl=" + msgCall.request().url().toString());
        if (msgResponse.isSuccessful()) {
            ResultMsg<DayData> resultMsg = msgResponse.body();
            if (resultMsg.getCode() == 1) {
                resultsMap = resultMsg.getData();
                errorCode = OP_SUCCESS;
                errorMsg = "获取数据成功";
            } else {
                errorCode = OP_SERVER_DENY_ERR;
                errorMsg = resultMsg.getMsg();
            }
        } else {
            errorCode = msgResponse.code();
            errorMsg = msgResponse.message();
        }
        return resultsMap;
    }

    public static MonthData getDriverDataByMonthRange(String driverId, Date startDate, Date endDate) throws IOException {
        MonthData resultsMap = null;
        Call<ResultMsg<MonthData>> msgCall =
                retrofitAccess.getDriverDataByMonthRange(TokenManager.getToken(),
                        driverId,
                        dateFormat.format(startDate),
                        dateFormat.format(endDate));
        Response<ResultMsg<MonthData>> msgResponse = msgCall.execute();
        Log.d(TAG, "getDriverDataByMonthRange: msgUrl=" + msgCall.request().url().toString());
        if (msgResponse.isSuccessful()) {
            ResultMsg<MonthData> resultMsg = msgResponse.body();
            if (resultMsg.getCode() == 1) {
                resultsMap = resultMsg.getData();
                errorCode = OP_SUCCESS;
                errorMsg = "获取数据成功";
            } else {
                errorCode = OP_SERVER_DENY_ERR;
                errorMsg = resultMsg.getMsg();
            }
        } else {
            errorCode = msgResponse.code();
            errorMsg = msgResponse.message();
        }
        return resultsMap;
    }

}
